﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using Microsoft.SharePoint;
using MediawikiSPMigratorClass;

namespace MediawikiSPMigratorConsole
{
    class Program
    {
        static void Main(string[] args)
        {

            string exportFilePath = ConfigurationManager.AppSettings["ExportFile"];
            XDocument exportFile = XDocument.Load(exportFilePath);

            string siteUrl = ConfigurationManager.AppSettings["SiteUrl"];
            string libraryName = ConfigurationManager.AppSettings["LibraryName"];
            LogData.WriteToLog("v0.12");
            LogData.WriteToLog("Started migration from " + exportFilePath + " into the library " + libraryName + " in site " + siteUrl);

            using (SPSite site = new SPSite(siteUrl))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList selectedList = web.Lists[libraryName];
                    List<string> errors = new List<string>();

                    LogData.WriteToLog("Migrating " + exportFile.Descendants("page").Count() + " pages");
                    foreach (XElement page in exportFile.Descendants("page"))
                    {
                        string pageFileName = page.Descendants("title").First().Value;
                        LogData.WriteToLog("Migrating " + pageFileName);
                        WikiData wikiData = new WikiData();

                        Dictionary<string, Dictionary<string, string>> templateDetails;
                        string output = wikiData.FormatWikiText(page.Descendants("text").First().Value, out templateDetails);
                        LogData.WriteToLog("Wiki output " + output);
                        try
                        {
                            MediawikiSPMigratorClass.SharePointData spData = new MediawikiSPMigratorClass.SharePointData(selectedList, templateDetails);
                            spData.CreatePage(pageFileName, output);
                        }
                        catch (Exception exp)
                        {
                            errors.Add(exp.ToString() + "\n");
                            LogData.WriteToLog("Error: " + exp.Message);
                        }
                        LogData.WriteToLog("Migrated " + pageFileName);
                    }
                }
            }
        }
    }
}